import React, {useState} from 'react';
import {Table, Card, Tag, Space, Row} from 'antd';

const weekDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];

function PersonalLessonTable({ week, data}) {
  week = week || 6;

  /**
   * 数据渲染，单元格课程数据渲染
   * @param value
   * @returns {JSX.Element}
   */
  const courseItem = value => {
    return (
      <Row align='center' justify='center'>
        <Space direction="vertical" align="center">
          <Tag color={value.backgroundColor}>{value.course_title}</Tag>
          <Tag color={value.backgroundColor}>{value.course_location}</Tag>
          <Tag color={value.backgroundColor}>{value.course_teacher}</Tag>
        </Space>
      </Row>
    );
  }

  /**
   * 获取列表中第一个匹配符合当前week的课程数据
   * @param couseList array 所有课程数据
   * @returns {null}
   */
  const getCourseAtNow = couseList => {
    let course = null;
    couseList.some(courseItem => {
      if (courseItem.course_weeks.indexOf(week) !== -1)
      {
        course = courseItem;
        return true;
      }
      return false;
    });
    return course;
  }

  /**
   * 单元格跨行处理
   * @param value
   * @returns {{children: string, props: {}}}
   */
  const renderContent = (value) => {
    const obj = {
      children: '',
      props: {}
    }
    let course = null;
    if (!(!value || value.length <= 0))
    {
      course = getCourseAtNow(value);
    }
    obj.children = course && courseItem(course);
    obj.props.rowSpan = course ? course.course_length : 1;
    return obj;
  }

  /**
   * 渲染单元格属性
   * @param record    行数据
   * @param rowIndex  行索引
   * @param colIndex  列索引
   * @returns {{style: {padding: number, height: string}}}
   */
  const cellStyle = (record, rowIndex, colIndex) => {
    const styles = {
      style: {
        padding: 0,
        height: '100px',
      }
    };
    let course = getCourseAtNow(record[colIndex]);

    if (course)
    {
      console.log(course, course.backgroundColor)
      styles.style.backgroundColor = course.backgroundColor
      styles.className ="ant-card-grid-hoverable";
      styles.style.border = 0;
    }
    return styles;
  }

  /**
   * 表格列初始化
   * @type {{dataIndex: string, title: string, render: (function(*, *, *): *)}[]}
   */
  const columns = [
    {
      title: 'Section',
      width: '100px',
      dataIndex: 'section',
    }
  ];
  weekDays.map(value => columns.push({width: '15%', title: value, dataIndex: value.toLowerCase(), render: renderContent, onCell: (record, rowIndex) => cellStyle(record, rowIndex, value)}))


  return <Table pagination={false} columns={columns} dataSource={convertPersonalTableRawDataToTableContent(data)} bordered />;
}


function randomHexColor() {
  return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).substr(-6);
}

function CourseData(week, title, teacher, location) {
  this.course_weeks = week;
  this.title = title;
  this.teacher = teacher;
  this.location = location;
}

function CourseInOneDay() {
  this.monday = [];
  this.tuesday = [];
  this.wednesday = [];
  this.thursday = [];
  this.friday = [];
  this.saturday = [];
  this.sunday = [];
}

/**
 * 将数据格式转换
 * @param data
 * @returns {any[]}
 */
function convertPersonalTableRawDataToTableContent(data) {
  let tableContent = new Array(11);
  let courseColor = {};
  for (let i = 0, len = tableContent.length; i < len; i++) {
    tableContent[i] = {
      section: '第' + (i+1) + '节',
      monday: [],
      tuesday: [],
      wednesday: [],
      thursday: [],
      friday: [],
      saturday: [],
      sunday: [],
    };
  }
  weekDays.forEach((weekday) => {
    console.log(data[weekday])
    data[weekday].forEach(lesson => {
      if (!courseColor.hasOwnProperty(lesson.course_title))
      {
        courseColor[lesson.course_title] = randomHexColor();
      }
      let requiredCourseInfo; // 需要存储的课程信息
      let lastCourseTime = -1; // 上一节课的时间
      lesson.course_time && lesson.course_time.forEach(currentCourseTime => {
        if (currentCourseTime - lastCourseTime > 1) {
          // 与上节课有间隔，需要创建一个课程，
          // 并保存其引用，方便对课程长度计数
          requiredCourseInfo = {
            course_length: 1,
            course_weeks: lesson.course_week,
            course_title: lesson.course_title,
            course_teacher: lesson.course_teacher,
            course_location: lesson.course_location,
            backgroundColor: courseColor[lesson.course_title]
          };
          tableContent[currentCourseTime - 1][weekday].push(requiredCourseInfo);
        } else if (currentCourseTime - lastCourseTime === 1) {
          // 通过引用，对已经插入课程的时间进行修改
          requiredCourseInfo.course_length++;
          let nullCourseInfo = {
            course_length: 0,
            course_weeks: lesson.course_week,
            course_title: lesson.course_title,
            course_teacher: lesson.course_teacher,
            course_location: lesson.course_location,
          }
          console.log(tableContent, currentCourseTime - 1)
          tableContent[currentCourseTime - 1][weekday].push(nullCourseInfo);
        }
        lastCourseTime = currentCourseTime;
      });
    });
  });
  return tableContent;
}

export default PersonalLessonTable;
